home *** CD-ROM | disk | FTP | other *** search
/ Night Owl 6 / Night Owl's Shareware - PDSI-006 - Night Owl Corp (1990).iso / 016a / gofer221.zip / IOSYNCH < prev    next >
Text File  |  1991-11-20  |  2KB  |  48 lines

  1. -- This file contains the example program from section 7.7 of the Haskell
  2. -- report (version 1.1) for a program using synchronisation.
  3.  
  4.  
  5. main :: Dialogue
  6. main  = readChan stdin abort (\userInput -> readNums (lines userInput))
  7.  
  8. readNums           :: [String] -> Dialogue
  9. readNums inputLines = readInt "Enter first number: " inputLines
  10.                         (\num1 inputLines1 ->
  11.                           readInt "Enter second number: " inputLines1
  12.                             (\num2 _ -> reportResult num1 num2))
  13.  
  14. reportResult       :: Int -> Int -> Dialogue
  15. reportResult num1 num2
  16.   = appendChan stdout ("Their sum is: "++ show (num1 + num2)) abort done
  17.                                   
  18.  
  19. -- readInt prints a prompt and then reads a line of input.  If the
  20. -- line contains an integer, the value of the integer is passed to the
  21. -- success continuation.  If a line cannot be parsed as an integer,
  22. -- an error message is printed and the user is asked to try again.
  23. -- If EOF is detected, the program is aborted.
  24.  
  25. readInt :: String -> [String] -> (Int -> [String] -> Dialogue) -> Dialogue
  26. readInt prompt inputLines succ
  27.   = appendChan stdout prompt abort
  28.       (case inputLines of
  29.          (l1 : rest) -> case (intRead l1) of
  30.                           [(n,"")] -> succ n rest
  31.                           _        -> appendChan stdout
  32.                                        "Error - retype the number\n" abort
  33.                                        (readInt prompt rest succ)
  34.          _           -> appendChan stdout "Early EOF" abort done)
  35.  
  36. -- Since the Gofer standard prelude does not include the reads function in
  37. -- the Text class, we have explicitly specified intRead in the definition
  38. -- above (rather than "reads" as used in the Haskell report).
  39. -- A straightforward (if rather crude) definition of this function follows:
  40.  
  41. intRead   :: String -> [(Int,String)]
  42. intRead "" = []
  43. intRead s  = loop 0 s
  44.              where loop n []        = [(n,"")]
  45.                    loop n s@(d:ds)
  46.                        | isDigit d  = loop (10*n+(ord d - ord '0')) ds
  47.                        | otherwise  = [(n,s)]
  48.